package org.terramagnet.mvcframework.resource;

import org.terramagnet.mvcframework.resource.service.LocalResourceService;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;
import org.terramagnet.mvcframework.asynchronous.PersistentAsynchrony;
import org.terramagnet.mvcframework.tools.Paginal;

/**
 * 资源清洁工.
 *
 * 提供同步和异步两种方式删除资源文件.
 *
 * @see #delete(java.io.File) 同步删除资源文件
 * @see #put(java.io.File) 将资源文件加入待删除列表
 *
 * @author lip
 */
@Component
public class ResourceCleaner extends PersistentAsynchrony<File> {

    @Resource
    private LocalResourceService localResourceService;

    @Override
    protected String getThreadName() {
        return "资源文件清理线程";
    }

    @Override
    protected void take(File data) {
        delete(data);
    }

    /**
     * 删除附件.
     *
     * 系统规定一个附件占一个文件夹。若传入的是文件夹，则删除整个目录（推荐方式）。
     * <p>
     * 如果删除单个文件后，会删除空目录。</p>
     *
     * @param file 要删除的附件
     */
    public void delete(File file) {
        if (!file.isDirectory()) {
            delete(file.getParentFile());
            return;
        }

        if(!localResourceService.isSecurity(file)){
            logger.warn("忽略不安全的文件删除：{}",file);
            return;
        }
        FileUtils.deleteQuietly(file);
        logger.debug("删除目录：{}", file.getAbsoluteFile());

        File directory = file.getParentFile();
        while (directory.length() == 0 && localResourceService.isSecurity(file)) {
            directory.delete();
            logger.debug("删除空文件夹：{}", directory.getAbsoluteFile());
            directory = directory.getParentFile();
        }
    }

    /**
     * 清理前两个星期到前一个星期的临时资源.
     */
    public void deleteTemporaryResource() {
        logger.debug("deleteTemporaryResource running.........................");
        int page = 1;
        int size = 80;

        Date now = new Date();
        Date to = DateUtils.truncate(DateUtils.addWeeks(now, -1), Calendar.DATE);
        Date from = DateUtils.addWeeks(to, -1);
        Paginal<ResourceArchive> resources = null;
        while (resources == null || !resources.isEmpty()) {
            resources = localResourceService.page(Boolean.TRUE, null, now, page, size);
//            清理前两个星期到前一个星期的临时资源
//            resources = localResourceService.page(Boolean.TRUE, from, to, page, size);
            if (!resources.isEmpty()) {
                localResourceService.delete(resources.getElements().toArray(new ResourceArchive[0]));
            }
        }

        logger.debug("deleteTemporaryResource finished.");
    }
}
